#include "report.h"
#include "ui_report.h"

#include <QFileDialog>
#include <QFile>
#include <QMessageBox>

Report::Report(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::Report)
{
    m_ui->setupUi(this);
    db = new CDBProvider("",this);
    te =  new TextEdit(this);
    loadTree();
}

Report::~Report()
{
    delete m_ui;
}

void Report::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Report::on_btnLoadResult_clicked()
{
    QStringList listFiles = QFileDialog::getOpenFileNames(this,
                                                          trUtf8("Загрузить результаты сканирования"),
                                                          ".",
                                                          tr("Result scanning (*.xml)"));
    foreach(QString fileName, listFiles){
        parseFileToBase(fileName);
    }
    loadTree();
}

void Report::parseFileToBase(QString fileName){
    QFile ioFile(fileName);
    QString errorMes;
    int     errorColum,
            errorLine;
    QDomDocument dom("Batch");
    if(!ioFile.open(QIODevice::ReadOnly)) return;
    if(!dom.setContent(&ioFile,false,&errorMes,&errorLine,&errorColum)){
        QMessageBox::warning(this,trUtf8("Ошибка парсера"),trUtf8("В файле - %1:\n строка - %3 колонка - %4\n %2").arg(fileName).arg(errorMes).arg(errorLine).arg(errorColum));
        ioFile.close();
        return;
    };
    QDomElement docElement = dom.documentElement();
    if(docElement.tagName() == "batch"){
        QDomElement e = docElement.firstChildElement();
        while(!e.isNull()){
            if(e.tagName()=="page") parsePageTobase(e);
            e = e.nextSiblingElement();
        }
    }
    ioFile.close();
}

void Report::parsePageTobase(QDomElement page){
    QDomNamedNodeMap atr = page.attributes();
    QDomElement e = page.firstChildElement();
    QString blockName;
    int i = 0, j = 0;
    Blank blank;
    while(!e.isNull()){
        if(e.tagName()== "block"){
            blockName = e.attribute("blockName");
            if(blockName == "shifr"){
                blank.shifr = e.text().toInt();               
            }else
                if(blockName.startsWith("r")){
                    i = blockName.mid(1,2).toInt()-1;
                    j = blockName.mid(3).toInt()-1;
                    blank.a[i][j] = (e.text() == "1");
                }else
                    if(blockName.startsWith("b")){
                        i = blockName.mid(1).toInt()-1;
                        blank.b[i] = e.text();
                    }else{
                        QMessageBox::information(this,trUtf8("Ошибка нода"),blockName);
                    }
                }
        e = e.nextSiblingElement();        
    }
    db->insertAnswerTester(blank);
}

void Report::on_btnPrint_clicked()
{
    QString body;
    if(m_ui->listToPrint->count() == 0) return;
    body += trUtf8("<center><H1>Апробация тестов</H1></center>\n");
    body += trUtf8("<h3>%1</h3>").arg(db->getStrinFromTree(m_ui->listToPrint->item(0)->data(Qt::UserRole).toInt()));
    QStringList l;
    body += trUtf8("Группы:<ul>");
    for(int i =0; i < m_ui->listToPrint->count();++i){
        body += tr("<li>%1</li>").arg(m_ui->listToPrint->item(i)->text());
        l.append(m_ui->listToPrint->item(i)->data(Qt::UserRole).toString());
    }    
    body += "</ul>";
    QString s = db->getReportTotal(l);
    if(s.isEmpty()) return;


    body += trUtf8("<p>%1</p>").arg(s);
    te->setHtmlText(QString("<html>\n<head></head><body>\n%1\n</body></html>").arg(body));
    te->showMaximized();
}

void Report::loadTree(){
    QTreeWidgetItem * i = new QTreeWidgetItem();
    i->setText(0,trUtf8("Разделы"));
    i->setIcon(0,QIcon(":/images/mac/fileopen.png"));
    i->setText(1,"0");
    i->setText(2,"topCat");
    m_ui->treeWidget->clear();
    m_ui->treeWidget->addTopLevelItem(i);
    i->addChildren(db->getTestFromDB(0));
    i->setExpanded(true);
}

void Report::on_btnAddPrint_clicked()
{
    //------------------------------------
    //   Надо исправить а то непорядок!
    //------------------------------------
    QTreeWidgetItem *ci = m_ui->treeWidget->currentItem();
    if(ci == NULL)return;
    else {
        QString s =  ci->text(0), s1=  ci->text(1);                
        QList<QListWidgetItem *> flist = m_ui->listToPrint->findItems(s,Qt::MatchFixedString);
        if(!flist.isEmpty())
            foreach(QListWidgetItem * f,flist)
                if(f->data(Qt::UserRole).toString() == s1) return;
        if(ci->text(2) != "test"){
            for(int t = 0; t < ci->childCount();++t){
                QTreeWidgetItem * chi= ci->child(t);
                if( chi->text(2) == "test"){
                    s = chi->text(0);
                    s1 =  chi->text(1);
                    flist = m_ui->listToPrint->findItems(s,Qt::MatchFixedString);
                    if(!flist.isEmpty())
                        foreach(QListWidgetItem * f,flist)
                            if(f->data(Qt::UserRole).toString() == s1) continue;                    
                    QListWidgetItem *i = new QListWidgetItem(m_ui->listToPrint);
                    i->setData(Qt::UserRole,s1);
                    i->setData(Qt::WhatsThisRole,chi->parent()->text(2));
                    i->setText(s);
                    m_ui->listToPrint->insertItem(m_ui->listToPrint->count(),i);
                }
            }
            return;
        }
//        if(m_ui->listToPrint->item(0))
//            if(ci->parent()->text(2) != m_ui->listToPrint->item(0)->data(Qt::WhatsThisRole).toString()){
//                QMessageBox::warning(this,trUtf8("Вы неправы"),trUtf8("нельзя добавить из другого раздела"));
//                return;
//            }
        QListWidgetItem *i = new QListWidgetItem(m_ui->listToPrint);
        i->setData(Qt::UserRole,s1);
        i->setData(Qt::WhatsThisRole,ci->parent()->text(2));
        i->setText(s);
        m_ui->listToPrint->insertItem(m_ui->listToPrint->count(),i);
    }
}

void Report::on_btnDelPrint_clicked()
{
    if( m_ui->listToPrint->currentItem())
        m_ui->listToPrint->currentItem()->~QListWidgetItem();
}

void Report::on_btnClearListPrint_clicked()
{
    m_ui->listToPrint->clear();
}
